from django.shortcuts import get_object_or_404
from django.contrib.auth.decorators import permission_required

from django.http import HttpResponse, HttpResponseRedirect

from jobs.models import Daemon, Job

from assets.models import Asset
from repositories.models import Repository
from files.models import File
from assets.modeljobs import AssetJob
  
from assets.util import HttpResponseSerialized, Fields


def damn_info(request):
  """
  Purpose: Discover general information about the health of the DAMN server.
  
  <a href="http://wiki.peragro.org/index.php/Tools/DAMN/API#damn.2Finfo.3Fformat.3D.28json.7Cxml.29">http://wiki.peragro.org/index.php/Tools/DAMN/API#damn.2Finfo.3Fformat.3D.28json.7Cxml.29</a>
  """
  info = {}
  info['daemons'] = []
  for d in Daemon.objects.all():
    info['daemons'].append(Fields(d, 'id', 'status', 'info', 'workers'))

  info['jobs'] = {}
  info['jobs']['scheduled'] = Job.objects.filter(status='scheduled').count()
  info['jobs']['completed'] = Job.objects.filter(status='successful').count()
  info['jobs']['error'] = Job.objects.filter(status='unsuccessful').count()
  
  info['jobs']['active'] = list(Job.objects.filter(status='running').values('content_type', 'method', 'object_id', 'pid'))

  info['repositories'] = []
  for r in Repository.objects.all():
    f = Fields(r, 'id', 'name')
    f['files'] = {}
    f['files']['total'] = File.objects.count()
    f['assets'] = {}
    f['assets']['total'] = Asset.objects.count()
    info['repositories'].append(f)
  
  info['brokenReferences'] = {}
  info['brokenReferences']['total'] = File.objects.filter(location=None).count()

  return HttpResponseSerialized(request, info)


@permission_required('assets.can_change_repository')
def repositories_scan(request, r_id):
  repository = get_object_or_404(Repository, id=r_id) 
  try:
    job = Job.objects.get(model=Repository, object_id=repository.id, method='scan')
  except Job.DoesNotExist:
    job = Job.objects.create_job(Repository, repository.id, 'scan')
    job.save()
  job._set_status('scheduled', ['defined', 'cancelled', 'successful', 'unsuccessful'])
  #return HttpResponseRedirect('/damn/repositories/'+str(r_id)+'/scan/status/')
  return HttpResponse('Scan for repository %s scheduled successfuly!'%(r_id))


#@permission_required('assets.can_change_repository')
def repositories_scan_status(request, r_id):
  repository = get_object_or_404(Repository, id=r_id)
  job = Job.objects.get(model=Repository, object_id=repository.id, method='scan')
  return HttpResponseSerialized(request, job)

  
@permission_required('assets.can_change_repository')
def files_analyze(request):
  files = File.objects.exclude(directory=True).exclude(repository=None)
  for file in files:
    try:
      job = Job.objects.get(model=File, object_id=file.id, method='analyze')
    except Job.DoesNotExist:
      job = Job.objects.create_job(File, file.id, 'analyze')
      job.save()
  jobs = Job.objects.filter(model=File, method='analyze', status='defined')
  jobs.update(status='scheduled')
  #return HttpResponseRedirect('/damn/files/analyze/status/')
  return HttpResponse('%d jobs scheduled for analyzing!'%(jobs.count()))

  
#@permission_required('assets.can_change_repository')
def files_analyze_status(request):
  info = {}
  jobs = Job.objects.filter(model=File, method='analyze')
  info['total'] = jobs.count()
  info['inprogress'] = jobs.filter(status__in=['scheduled', 'running']).count()
  
  info['successful'] = jobs.filter(status='successful').count()
  info['unsuccessful'] = jobs.filter(status='unsuccessful').count()

  return HttpResponseSerialized(request, info)
  
  
@permission_required('assets.can_change_repository')
def assets_transcode(request):
  assets = AssetJob.objects.exclude(file__location=None)
  for asset in assets:
    try:
      job = Job.objects.get(model=Asset, object_id=asset.id, method='transcode_cache')
    except Job.DoesNotExist:
      job = Job.objects.create_job(asset, 'transcode_cache')
      job.save()
  jobs = Job.objects.filter(model=Asset, method='transcode_cache', status='defined')
  jobs.update(status='scheduled')
  return HttpResponse('%d jobs scheduled for transcoding!'%(jobs.count()))

  
#@permission_required('assets.can_change_repository')
def assets_transcode_status(request):
  info = {}
  jobs = Job.objects.filter(model=Asset, method='transcode_cache')
  info['total'] = jobs.count()
  info['inprogress'] = jobs.filter(status__in=['scheduled', 'running']).count()
  
  info['successful'] = jobs.filter(status='successful').count()
  info['unsuccessful'] = jobs.filter(status='unsuccessful').count()

  return HttpResponseSerialized(request, info)
